import json
import httpx
import sys
import os
from mcp.server import FastMCP

server = FastMCP("天气预报")

AMAP_URL = "https://restapi.amap.com"
MAP_KEY = os.getenv("MAP_KEY", "10d653c94cd1009946a54a0e0a8cacab")


@server.tool("get_weather_forecast")
async def get_weather_forecast(location: str) -> str:
    """
    根据地址查询天气预报的信息
    Args:
        location: 需要查询天气的地址或城市名称
    Returns:
        天气信息的JSON字符串
    """
    async with httpx.AsyncClient() as http_client:
        try:
            geo_response = await http_client.get(
                f"{AMAP_URL}/v3/geocode/geo",
                params={"key": MAP_KEY, "address": location},
            )
            sys.stderr.write(location + geo_response.text)
            if geo_response.status_code != 200:
                return (
                    f"地址编码请求失败:{geo_response.status_code}-{geo_response.text}"
                )
            geo_data = json.loads(geo_response.text)
            if geo_data["status"] != "1":
                return f"地址编码查询错误:{geo_data['info']}"
            city_code = geo_data["geocodes"][0]["adcode"]
            weather_response = await http_client.get(
                f"{AMAP_URL}/v3/weather/weatherInfo",
                params={"key": MAP_KEY, "city": city_code},
            )
            weather_data = json.loads(weather_response.text)
            if weather_data["status"] != "1":
                return f"天气查询错误:{weather_data['info']}"
            return weather_response.text

        except Exception as error:
            return f"查询天气时发生异常:{str(error)}"


if __name__ == "__main__":
    server.run(transport="stdio")
